#include <db/db.h>
#include <db/db_private.h>

#include <utitl/logger.h>

namespace ECG
{
namespace DB
{
    DB_Redis* DB_Redis::m_dbRedis=NULL;

    DB_Redis::DB_Redis():d_ptr(new DB_RedisPrivate(this))
    {
        E_D(DB_Redis);
        //d->cluster = new  acl::redis_client_cluster();
        d->redis = new acl::redis_list();
        d->client = NULL;
        //d->clietn = new acl::redis_client();
    }

    DB_Redis::~DB_Redis()
    {
        E_D(DB_Redis);
        // release redis_list
        if(d->redis)
        {
            log_debug() << "clear redis list";
            d->redis->clear();
            delete d->redis;
            d->redis = NULL;
        }
        // release client
        if(d->client)
        {
            log_debug() << "close redis client";
            d->client->close();
            delete d->client;
            d->redis = NULL;
        }
        // release private data
        delete d;

    }

    bool DB_Redis::connect(const char*addr,const char* passwd,int conn_timeout)
    {
        E_D(DB_Redis);
        d->client = new acl::redis_client(addr,conn_timeout);
        log_debug() << "redis connect addr: " << addr;
        if(NULL != passwd)
        {
            d->client->set_password(passwd);
            log_debug() << "redis connect passwd: " << passwd;
        }
        d->redis->set_client(d->client);
        return true;
    }

    DB_Redis* DB_Redis::instance()
    {
        if(NULL != m_dbRedis)
        {
            return m_dbRedis;
        }
        m_dbRedis = new DB_Redis();
        return m_dbRedis;   
    }

    void DB_Redis::destroy()
    {
        if(NULL != m_dbRedis)
        {
            delete m_dbRedis;
        }
        m_dbRedis = NULL;
    }


    int DB_Redis::lpush(const char* key, const char* values[], const size_t lens[],size_t argc)
    {
        E_D(DB_Redis);
        return d->redis->lpush(key,values,lens,argc);
    } 
     
    int DB_Redis::rpush(const char* key, const char* values[], const size_t lens[],size_t argc)
    {
        E_D(DB_Redis);
        return d->redis->rpush(key,values,lens,argc);
    } 
    
    int DB_Redis::length(const char* key)
    {
        E_D(DB_Redis);
        return d->redis->llen(key);
    } 
    
    int DB_Redis::lpop(const char* key, acl::string& buf)
    {
        E_D(DB_Redis);
        return d->redis->lpop(key,buf);
    }
    
    int DB_Redis::rpop(const char* key, acl::string& buf)
    {
        E_D(DB_Redis);
       return d->redis->rpop(key,buf);
    } 

}
}



